import 'package:auto_route/auto_route.dart';

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:get_it/get_it.dart';
import 'package:provider/provider.dart';

import '../../config/route/bt_app_router.dart';
import '../../config/route/bt_app_router.gr.dart';
import '../../data/stats/bt_log_pages.dart';
import '../../data/stats/bt_log_pv_manger.dart';
import '../../data/store/bt_hive_logon_store.dart';
import '../../utils/bt_tool_utils.dart';
import 'models/bt_boot_model.dart';
import 'repository/bt_boot_repository.dart';

@RoutePage(name: "btBootRoute")
class BtBootPage extends StatefulWidget {
  const BtBootPage({super.key});

  @override
  State<BtBootPage> createState() => _BtBootPageState();
}

class _BtBootPageState extends State<BtBootPage> {
  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) async {
      await Future.delayed(const Duration(seconds: 2));
      routerPage();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  void routerPage() async {
    bool showed = await isGuideShowed();
    if (!showed) {
      GetIt.instance<BtAppRouter>().replaceAll([const GuideRoute()]);
      return;
    }

    var data = await BtHiveLogonStore().getData();
    String accessToken = data?.token ?? '';
    if (accessToken.isNotEmpty) {
      BtBootRepository().validToken(accessToken, (success, msg) {
        if (success) {
          GetIt.instance<BtAppRouter>().replaceAll([const HostMainRoute()]);
        } else {
          GetIt.instance<BtAppRouter>().replaceAll([const BtLoginRoute()]);
        }
      });
    } else {
      GetIt.instance<BtAppRouter>().replaceAll([const BtLoginRoute()]);
    }

    BtLogPvManger.stat(page: BtLogPages.launch);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ChangeNotifierProvider(
        create: (context) => BtBootModel(),
        child: Consumer<BtBootModel>(builder: (context, model, _) {
          return Stack(
            children: [
              SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: Image.asset(
                  'assets/images/bt_login_bg.png',
                  fit: BoxFit.fill,
                ),
              ),
            ],
          );
        }),
      ),
    );
  }
}
